<template>
  <div>
    <div class="table">
      <div class="titlebox">
        <div class="text"></div>
        <div
          class="right"
          :style="{ alignItems: 'center', lineHeight: '32.5px' }"
        >
          <button
            type="primary"
            size="small"
            class="bewdao daochu"
            @click="dialogOpen"
          >
            新增
          </button>
          <el-tooltip class="item" effect="dark" content="刷新" placement="top">
            <span
              @click="shuaxin"
              :style="{ cursor: 'pointer', fontSize: '20px' }"
              ><i class="el-icon-refresh-right"></i
            ></span>
          </el-tooltip>
          <el-dropdown trigger="click" @command="command">
            <span class="el-dropdown-link">
              <el-tooltip
                class="item"
                effect="dark"
                content="密度"
                placement="top"
              >
                <span :style="{ cursor: 'pointer', fontSize: '20px' }"
                  ><i class="el-icon-d-caret"></i
                ></span>
              </el-tooltip>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item class="dropdown-list" command="默认"
                >默认</el-dropdown-item
              >
              <el-dropdown-item class="dropdown-list" command="中等"
                >中等</el-dropdown-item
              >
              <el-dropdown-item class="dropdown-list" command="紧凑"
                >紧凑</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <el-table
        v-loading="loading"
        :data="tableList"
        default-expand-all
        height="350px"
        border
        ref="Indextable"
        :size="iissize"
        :header-cell-style="{
          background: '#f5f5f5',
          'text-align': 'center',
        }"
      >
        <template slot="empty">
          <el-empty description="暂无数据"></el-empty>
        </template>
        <el-table-column align="left" prop="indexName" label="索引名称">
        </el-table-column>
        <el-table-column align="left" prop="bizFieldCodes" label="关联字段">
          <template slot-scope="scope">
            <span>{{ scope.row.bizFieldCodes.join(",") }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" prop="indexType" label="索引类型">
          <template slot-scope="scope">
            <span>{{
              indexType.find((i) => i.value === scope.row.indexType).text
            }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="150" label="操作">
          <template slot-scope="scope">
            <div class="table-cz">
              <el-tooltip
                class="item"
                effect="dark"
                content="编辑"
                placement="top"
              >
                <i
                  style="
                    font-size: 14px;
                    color: rgb(64, 149, 229);
                    cursor: pointer;
                  "
                  class="el-icon-edit"
                  @click="edit(scope.row)"
                ></i
              ></el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="删除"
                placement="top"
              >
                <i
                  style="font-size: 14px; color: red; cursor: pointer"
                  class="el-icon-delete"
                  @click="del(scope.row)"
                ></i
              ></el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      :show-close="true"
      :visible.sync="dialogVisible"
      v-if="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :before-close="diaClose"
      append-to-body
      :center="true"
    >
      <el-form
        ref="dialogForm"
        :rules="dialogRules"
        :model="dialogForm"
        label-width="110px"
      >
        <el-form-item label="索引类型" prop="indexType">
          <el-select
            :disabled="diaType === 'edit'"
            @change="change"
            v-model="dialogForm.indexType"
          >
            <el-option
              v-for="item in indexType"
              :key="item.value"
              :label="item.text"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="索引名称" prop="indexName">
          <el-input
            :disabled="this.dialogForm.indexType === 'pk' || diaType === 'edit'"
            v-model="dialogForm.indexName"
          ></el-input>
        </el-form-item>
        <div class="add">
          <button
            type="primary"
            size="small"
            class="add-button"
            @click="fieldOpen"
          >
            新增
          </button>
        </div>
        <el-table
          v-loading="loading"
          :data="addList"
          default-expand-all
          style="width: 100%"
          height="300px"
          border
          ref="table"
          :size="iissize"
          :header-cell-style="{
            background: '#f5f5f5',
            'text-align': 'center',
          }"
        >
          <template slot="empty">
            <el-empty description="暂无数据"></el-empty>
          </template>

          <el-table-column align="left" prop="tableColumnName" label="关联字段">
          </el-table-column>
          <el-table-column align="center" width="150" label="操作">
            <template slot-scope="scope">
              <div class="table-cz">
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="删除"
                  placement="top"
                >
                  <i
                    style="font-size: 14px; color: red; cursor: pointer"
                    class="el-icon-delete"
                    @click="fieldDel(scope.row)"
                  ></i
                ></el-tooltip>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="上移"
                  placement="top"
                >
                  <i
                    style="
                      font-size: 14px;
                      color: rgb(64, 149, 229);
                      cursor: pointer;
                    "
                    class="el-icon-upload2"
                    @click="fieldMove('up', scope.$index, scope.row)"
                  ></i
                ></el-tooltip>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="下移"
                  placement="top"
                >
                  <i
                    style="
                      font-size: 14px;
                      color: rgb(64, 149, 229);
                      cursor: pointer;
                    "
                    class="el-icon-download"
                    @click="fieldMove('down', scope.$index, scope.row)"
                  ></i
                ></el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div style="margin-top: 20px; text-align: center">
        <span slot="footer" class="dialog-footer">
          <el-button @click="diaClose">取 消</el-button>
          <el-button type="primary" @click="Submit">保 存</el-button>
        </span>
      </div>
    </el-dialog>
    <el-dialog
      :show-close="true"
      :visible.sync="fieldVisible"
      v-if="fieldVisible"
      width="1000px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      append-to-body
      :center="true"
    >
      <TableUse
        v-loading="loading2"
        :data="fieldList"
        border
        max-height="400px"
        ref="table"
        :header-cell-style="{
          background: '#f5f5f5',
          'text-align': 'center',
        }"
        :default="defaultList"
        :tableConfig="tableConfig"
        :name="'tableColumnName'"
        @selection-change="chooseList"
      >
        <template v-slot:nullEnable="row">
          {{ row.row.nullEnable ? "是" : "否" }}
        </template>
        <template v-slot:fieldType="row">
          {{ propTypeList.find((i) => i.value === row.row.fieldType)?.text }}
        </template>
      </TableUse>
      <div style="margin-top: 20px; text-align: center">
        <span slot="footer" class="dialog-footer">
          <el-button @click="fieldVisible = false">取 消</el-button>
          <el-button type="primary" @click="tableSubmit">确 定</el-button>
        </span>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addIndexApi,
  delIndexApi,
  editIndexApi,
  getIndexDataApi,
  getIndexListApi,
  getPropertyListApi,
  getPropTypeListApi
} from '@/api/Model-all/Model-business'
import TableUse from '../components/TableUse.vue'
export default {
  name: 'IndexMaintain',
  components: { TableUse },
  props: {
    data: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {
      diaType: 'add',
      iissize: 'medium',
      loading: false,
      loading2: false,
      tableList: [],
      actionList: [],
      addList: [],
      choose: '',
      fieldList: [],
      dialogForm: {},
      indexType: [
        {
          text: '主键索引',
          value: 'pk'
        },
        {
          text: '唯一索引',
          value: 'uk'
        },
        {
          text: '普通索引',
          value: 'idx'
        }
      ],
      propTypeList: [],
      dialogRules: {
        indexType: [
          { required: true, message: '请选择索引类型', trigger: 'change' }
        ],
        indexName: [
          { required: true, message: '请输入索引名称', trigger: 'blur' }
        ]
      },
      tableConfig: [
        {
          align: 'left',
          prop: 'bizFieldCode',
          label: '属性编码'
        },
        {
          align: 'left',
          prop: 'bizFieldName',
          label: '属性名称'
        },
        {
          align: 'left',
          prop: 'dataType',
          label: '数据类型'
        },
        {
          align: 'left',
          prop: 'nullEnable',
          label: '是否可空'
        },
        {
          align: 'right',
          prop: 'dataLength',
          label: '数据长度'
        },
        {
          align: 'right',
          prop: 'dataPrecision',
          label: '数据精度'
        }
      ],
      dialogVisible: false,
      itemVisible: false,
      fieldVisible: false
    }
  },
  created () {
    this.getPropTypeList()
  },
  mounted () {
    this.getIndexList()
    this.getTableList()
  },
  watch: {
    dialogForm: {
      handler (val) {
        if (val.indexType === 'pk') {
          this.$set(this.dialogForm, 'indexName', 'PRIMARY')
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    defaultList () {
      return this.addList
    },
    codeList () {
      return this.addList.map((i) => i.tableColumnName).join(',')
    }
  },
  methods: {
    // 获取属性类型
    async getPropTypeList () {
      const res = await getPropTypeListApi()
      this.propTypeList = res.data.list
    },

    // 查询索引列表
    async getIndexList () {
      this.loading = true
      const res = await getIndexListApi(this.data.bizModelId)
      this.tableList = res.data.list
      console.log('tableList', res)
      this.loading = false
    },

    // 查询新增表字段列表
    async getTableList () {
      console.log(this.data)
      this.loading2 = true
      const res = await getPropertyListApi(this.data.bizModelId)
      this.fieldList = res.data.list
      this.loading2 = false
    },

    command (val) {
      if (val === '默认') {
        this.iissize = 'medium'
      } else if (val === '中等') {
        this.iissize = 'small'
      } else {
        this.iissize = 'mini'
      }
    },

    async del (item) {
      console.log(item)
      this.$confirm('请确认是否删除该业务模型索引?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          console.log(1)
          const res = await delIndexApi(item.bizIndexId)
          console.log(res)
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: res.message,
              duration: 2000
            })
            this.getIndexList()
          } else {
            this.$message({
              type: 'error',
              message: res.message,
              duration: 2000
            })
          }
        })
        .catch((action) => {
          if (action === 'cancel') {
            this.$message({
              type: 'info',
              message: '已取消删除',
              duration: 2000
            })
          }
        })
    },
    //  新增 弹窗
    dialogOpen (type) {
      this.diaType = 'add'
      this.$set(this.dialogForm, 'indexType', this.indexType[0].value)
      this.dialogVisible = true
    },
    fieldOpen () {
      this.fieldVisible = true
    },
    async edit (item) {
      this.diaType = 'edit'
      console.log(item)
      // 查询业务模型索引信息
      const res = await getIndexDataApi(item.bizIndexId)
      console.log(res)
      const data = res.data.entity
      this.$set(this.dialogForm, 'indexName', data.indexName)
      this.$set(this.dialogForm, 'indexType', data.indexType)
      this.$set(this.dialogForm, 'bizIndexId', data.bizIndexId)
      console.log(this.dialogForm)
      this.getList(data.bizFieldCodes)
      console.log(this.dialogForm)
      console.log('addList', this.addList)

      this.dialogVisible = true
    },
    change (val) {
      console.log(val)
      if (val !== 'pk') {
        this.$set(this.dialogForm, 'indexName', '')
      }
    },
    shuaxin () {
      this.getIndexList()
      this.$message({
        message: '列表刷新成功',
        type: 'success',
        duration: 2000
      })
    },
    // 分组 提交
    async Submit () {
      await this.$refs.dialogForm.validate()
      const res =
        this.diaType === 'add'
          ? await addIndexApi({
            bizModelId: this.data.bizModelId,
            ...this.dialogForm,
            fieldCode: this.codeList
          })
          : await editIndexApi({
            bizIndexId: this.dialogForm.bizIndexId,
            ...this.dialogForm,
            fieldCode: this.codeList
          })
      console.log(res)
      if (res.code == 200) {
        this.$message({
          message: res.message,
          type: 'success',
          duration: 2000
        })
        this.getIndexList()
        this.diaClose()
      } else {
        this.$message({
          message: res.message,
          type: 'error',
          duration: 2000
        })
      }
    },
    // 过滤新增列表
    getList (list) {
      const newArr = []
      list.forEach((tableColumnName) => {
        newArr.push(
          this.fieldList.find(
            (i) =>
              i.tableColumnName.toLowerCase() == tableColumnName.toLowerCase()
          )
        )
      })
      this.addList = newArr
    },
    // 新增字段表选择确认
    async tableSubmit () {
      console.log(this.fieldList)
      const list = this.choose.split(',')
      this.getList(list)
      this.fieldVisible = false
      console.log(this.addList)
      // this.addList
    },
    chooseList (arr) {
      console.log(arr)
      this.choose = arr
    },

    removeItem (item) {
      const index = this.addList.findIndex(
        (i) => i.bizFieldCode === item.bizFieldCode
      )
      if (index !== -1) {
        this.addList.splice(index, 1)
      }
    },
    // 新增字段表删除
    fieldDel (item) {
      this.removeItem(item)
    },
    fieldMove (type, index, item) {
      console.log(item)

      if (type === 'up') {
        if (index !== 0) {
          const temp = this.addList[index - 1]
          this.$set(this.addList, index - 1, this.addList[index])
          this.$set(this.addList, index, temp)
        }
      } else {
        if (index !== this.addList.length - 1) {
          const i = this.addList[index + 1]
          this.$set(this.addList, index + 1, this.addList[index])
          this.$set(this.addList, index, i)
        }
      }
    },
    diaClose () {
      this.dialogVisible = false
      this.fieldVisible = false
      this.dialogForm = {}
      this.addList = []
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-select {
  width: 100%;
}
:v-deep.el-table th.gutter{
  display: none;
  width:0
}
::v-deep.el-table colgroup col[name='gutter']{
  display: none;
  width: 0;
}
::v-deep.el-table__body{
  width: 100% !important;
}
.table-cz {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-around;
}
.button {
  width: 63px;
  height: 32px;
  margin-right: 5px;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 3px;
}

.top {
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: 80px;
  background-color: #fff;
  border-bottom: 1px solid #f1f1f1;
  margin-bottom: 20px;
  align-items: center;
  .left {
    display: flex;
    align-items: center;
    .group-select {
      width: 200px;
      margin-right: 10px;
    }
    .group-add {
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      border: 1px solid #dcdfe6;
      border-radius: 5px;
      width: 25px;
      height: 25px;
      margin-right: 20px;
    }
  }
}
.add {
  display: flex;
  justify-content: flex-end;
  .add-button {
    width: 64px;
    height: 32px;
    margin-bottom: 10px;
    background-color: #1890ff;
    color: #fff;
    border: none;
    border-radius: 3px;
  }
}
.table {
  .titlebox {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    .text {
      font-size: 16px;
    }
    .right {
      align-items: center;
      i {
        margin-left: 10px;
      }
      .bewdao {
        padding: 0 15px;
        height: 32px;
        margin-right: 20px;
      }
      .daochu {
        background-color: #1890ff;
        color: #fff;
        border: none;
        border-radius: 3px;
      }
    }
  }
}
</style>
